<template>
  <el-popover
    ref="popover"
    :title="(formData.id ? '编辑': currentNode ? '添加子' : '添加') + '条件信息'"
    v-model="visible"
    width="320"
    popper-class="con-popover"
    @show="show"
  >
    <el-form v-if="visible" ref="form" :model="formData" size="mini">
      <el-row :gutter="6">
        <el-col :span="12">
          <el-form-item

            :rules="{
          required: true, message: '元素不能为空', trigger: 'blur'
        }"
            prop="el">
            <el-select v-model="formData.el" placeholder="请选择元素" value-key="id" @change="comparingEls">
              <el-option :key="index" :value="item.originalData" :label="item.label"
                         v-for="(item, index) in conditionElements"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :rules="{
          required: true, message: '关系不能为空', trigger: 'blur'
        }"
            prop="el">
            <el-select v-if="!formData.el || !isSwitch()" @change="valueEl"
                       v-model="formData.compare" placeholder="请选择关系" value-key="value">
              <el-option :key="index" :value="item" :label="item.label"
                         v-for="(item, index) in compareEls"></el-option>
            </el-select>
            <el-switch v-else-if="isSwitch()" v-model="formData.value"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item v-if="valueType==='input'" :rules="valueRules" prop="value">
        <el-input v-model="formData.value"></el-input>
      </el-form-item>
      <el-form-item v-if="valueType==='number'" :rules="valueRules" prop="value">
        <el-input-number :style="{width: '100%'}" v-model="formData.value" v-bind="valueProps"></el-input-number>
      </el-form-item>

      <el-form-item v-if="['choice', 'choiceMulti'].includes(valueType)" :rules="valueRules" prop="value">
        <el-select :style="{width: '100%'}" v-model="formData.value" v-bind="valueProps" value-key="value">
          <el-option :key="index" v-for="(item, index) in options" :value="item" :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <el-row v-else-if="valueType==='numberRange'" :gutter="6">
        <el-col :span="12">
          <el-form-item :rules="valueRules" prop="value.start">
            <el-input-number :style="{width: '100%'}" v-model="formData.value.start" v-bind="valueProps.start"
                             placeholder="开始值"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :rules="valueRules" prop="value.end">
            <el-input-number :style="{width: '100%'}" v-model="formData.value.end" v-bind="valueProps.end"
                             placeholder="开始值"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: right; margin-top: 5px">
        <el-button size="mini" type="text" @click="visible = false">取消</el-button>
        <el-button type="primary" size="mini" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>

    <span slot="reference">
      <slot name="reference"></slot>
    </span>

  </el-popover>
</template>

<script>
import {
  ConditionPropsMappings,
  ConditionMappings,
  Conditions,
} from './condition'
import conditionMinix from './condition-minix'

import JSONPath from 'jsonpath'
import { utils } from '@/libs/utils'

export default {
  name: 'form-popover',
  mixins: [conditionMinix],
  props: {
    value: {
      type: Object,
      default() {
        return {}
      }
    },
    currentNode: {
      type: Object | undefined,
      default() {
        return undefined
      }
    },
    conditionElements: {
      type: Array,
      default() {
        return []
      }
    },
    handleSubmitEvent: Function
  },
  inject: ['getEditor'],
  data() {
    return {
      visible: false,
      formData: _.cloneDeep(this.value),
      valueType: '',
      valueProps: {},
      options: [],
      valueRules: [{
        required: true,
        message: '值不能为空',
        trigger: 'blur'
      }],
      compareEls: []
    }
  },
  created() {
    this.comparingEls()
    this.valueEl()
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const newFormData = _.cloneDeep(this.formData)

          newFormData['label'] = this.getFormattedLabel(newFormData)
          this.$emit('handle-submit-event', newFormData, this.currentNode)
          if (!this.formData.id) {
            this.formData = {}
            this.valueType = ''
          }
          this.visible = false
        }
      })
    },
    // 格式化label
    getFormattedLabel(data) {
      const elName = data.el.options.label
      let value = data.value
      if (_.isArray(value)) {
        value = value.map(({ label }) => label).join(', ')
      }
      let formattedValue = ''
      if (data.compare.format) {
        formattedValue = utils.format(data.compare.format, _.isString(value) ? { value: value } : value)
      } else if (data.el.type === 'switch') {
        formattedValue = data.value ? '为真' : '为假'

      } else {
        formattedValue = utils.format(ConditionMappings['common'], {
          compare: data.compare.label,
          value
        })
      }
      return `"${elName}" 的值 ${formattedValue}`
    },
    // 打开弹出框关闭其他弹出框
    show() {
      _.each(this.getEditor().$refs, (ref, name) => {
        if (name.indexOf('popover-') > -1) {
          if (ref && ref !== this) {
            if (ref.doClose) {
              ref.doClose()
            } else {
              ref.$refs.popover.doClose()
            }
          }
        }
      })
    },
    // 根据选择元素的类型自动筛选最合适的比较运算
    comparingEls(el) {
      if (!this.formData.el) {
        return
      }
      if (el) {
        this.valueType = ''
        this.formData.compare = ''
        this.initValue()
      }
      const name = this.getCompName()
      const key = Object.keys(Conditions).find(key => key.indexOf(name) > -1)
      this.compareEls = Conditions[key]
    },
    // 根据选择元素和比较运算符智能选择value框
    valueEl(el) {
      if (!this.formData.el || !this.formData.compare) {
        return
      }
      if (el) {
        this.initValue()
      }
      this.valueType = this.getCompName()
      if (this.isChoiceMulti() || this.isChoice()) {
        this.options = this.getOptions()
      }
      // 生产对应的属性
      this.valueProps = utils.productJson(this.formData.el, ConditionPropsMappings[this.valueType])
    },
    // 下拉框选项
    getOptions() {
      return JSONPath.query(this.formData.el, '$.options.optionItems', 1)[0] || []
    },
    // 初始化
    initValue() {
      if (this.isChoiceMulti()) {
        this.$set(this.formData, 'value', [])
      } else if (this.isNumberBetween()) {
        this.$set(this.formData, 'value', {
          start: 0,
          end: 0
        })
      } else if (this.isNumber()) {
        this.$set(this.formData, 'value', 0)
      } else if (this.isSwitch()) {
        this.$set(this.formData, 'value', false)
      } else {
        this.$set(this.formData, 'value', '')
      }
    },
  }
}
</script>

<style lang="scss">
.con-popover {
  .el-popover__title {
    font-size: 14px;
  }
}

</style>
